﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;

namespace ResourceReportBuilder
{
    public class MimeTypeCollection : List<MimeType>
    {
        private static MimeTypeCollection _instance = new MimeTypeCollection();
        public static MimeTypeCollection FilledInstance
        {
            get 
            {
                if (_instance.Count == 0)
                {
                    _instance = GetMimeTypeList();
                }
                return _instance;
            }
        }

        public bool ContainsMimeType(string mimeType, string extension)
        { 
            return this.Count(item=> item.Type == mimeType && item.Extension == extension) != 0;
        }

        public static MimeTypeCollection GetMimeTypeList()
        {
            MimeTypeCollection tbl = new MimeTypeCollection();
            tbl.Add(new MimeType("", "application/unknown"));

            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(File.ReadAllText("mimeTypes.xml"));
            XmlElement root = xdoc.DocumentElement;

            foreach (XmlNode rt in root.ChildNodes)
            {
                if (rt.NodeType != XmlNodeType.Element)
                {
                    continue;
                }
                string mtExt = rt.Attributes["Extension"] != null ? rt.Attributes["Extension"].Value : null;
                if (string.IsNullOrWhiteSpace(mtExt))
                {
                    continue;
                }
                MimeType mt = new MimeType(mtExt, rt.InnerText);
                if (tbl.ContainsMimeType(rt.InnerText, mtExt))
                {
                    continue;
                }
                string strSubst = rt.Attributes["PerformSubstitution"] != null ? rt.Attributes["PerformSubstitution"].Value : null;
                bool b;
                if (bool.TryParse(strSubst, out b))
                {
                    mt.PerformSubstitution = b;
                }

                tbl.Add(mt);
            }

            return tbl;
        }
    }
}
